# -*- coding: UTF-8 -*-

'''
Created on 17.06.2014

@author: MathiasAr
'''

import os, sys
import StringIO

from gtk._gtk import Button
import ImageColor

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
except:
    sys.exit(1)

import ImageTrim, Image
import ImageHelper
from ImageHelper import AutoOrientImage, GetImageOrientation
from gtkImageAppBase import GtkImageAppBase

class GtkImageTrim(GtkImageAppBase):

    def __init__(self):
        ########################################################
        # base application frame
        GtkImageAppBase.__init__(self)
        
        ########################################################
        # application specific widgets
        self._gladeTrim = "gtkImageTrim.glade"
        self._wAppTrim = gtk.glade.XML(self._gladeTrim, "vbox1")
        self._trimRoot = self._wAppTrim.get_widget("vbox1")
        self._bkgColors = self._wAppTrim.get_widget("table1")
        self._bkgColors.resize(5, 1)
        self._column = 0
        self._row = 0
        self._backgrdColors = []
        
        # connect signals
        self._colorBtn = self._wAppTrim.get_widget("colorbutton1")
        self._colorBtn.connect("color-set", self.onColorSelected)
        self._exitButton = self._wAppTrim.get_widget("button2")
        self._exitButton.connect("pressed", self.quit)
        self._startButton = self._wAppTrim.get_widget("button1")
        self._startButton.connect("pressed", self.onStart)
        self._trimRunning = False
        self._targetChooser = self._wAppTrim.get_widget("filechooserbutton2")
        self._previewImage = self._wAppTrim.get_widget("image1")
        self._previewImage.connect("key-press-event", self.onPreview)
        self._colorTolerance = self._wAppTrim.get_widget("spinbutton1")
        
        ########################################################
        # insert specific widgets into base application
        gtkLabel = gtk.Label("Trim")
        self.append(self._trimRoot, gtkLabel)
        
        
    def onColorSelected(self, widget):
        gtkColor = widget.props.color
        btn = gtk.Button()
        color = ImageHelper.GtkColorToRGB(gtkColor)
        btn.connect("pressed", self.onColorRemove, color)
        btn_color = btn.get_colormap()
        btn_color = btn_color.alloc_color(gtkColor)
        btn_style = btn.get_style().copy()
        btn_style.bg[gtk.STATE_NORMAL] = gtkColor
        btn.set_style(btn_style)
        btn.set_size_request(20, 20)
        
        if not color in self._backgrdColors:
            self._backgrdColors.append(color)
        
        # add to table
        self._bkgColors.attach(btn, self._column, self._column + 1, self._row, self._row + 1)
        self._column += 1
        if self._column >= 5:
            self._column = 0
            self._row += 1
            self._bkgColors.resize(self._row + 1, 5)
            pass
        
        btn.show()
        pass
        
    def onColorRemove(self, widget, data):
        if data in self._backgrdColors:
            self._backgrdColors.remove(data)
        self._bkgColors.remove(widget)
        pass
        
    def onPreview(self, widget):
        files = self.getFiles()
        if files and len(files) > 0:
            self.setPreview(Image.open(files[0], "r"))
        pass
        
    def setPreview(self, im):
        im.thumbnail((320, 240))
        pixbuf = ImageHelper.GetGtkPixbuf(im)
        self._previewImage.set_from_pixbuf(pixbuf)

    def onStart(self, widget):
        if self._trimRunning:
            self._trimRunning = False
            return
        # get select files from Picture tab
        imageFiles = self.getFiles()
        rootFolder = self.getRootFolder()
        if (not imageFiles or not rootFolder): return
        
        self._trimRunning = True
        self._startButton.set_label("Cancel")
        
        for imageFile in imageFiles:
            if (not self._trimRunning): break
            relFile = imageFile[len(rootFolder):].strip(os.path.sep)
            targetFolder = self._targetChooser.get_filename().decode(encoding='UTF-8')
            targetFile = targetFolder + os.path.sep + relFile.replace(os.path.sep, "_")
            colorTolerance = self._colorTolerance.get_value()
            im = ImageTrim.imageTrim(imageFile, self._backgrdColors, int((256 * colorTolerance) / 100))
            gtk.main_iteration()
            im.save(targetFile)
            gtk.main_iteration()
            self.setPreview(im)
            gtk.main_iteration()
            
        self._trimRunning = False
        self._startButton.set_label("Start")
        

if __name__ == '__main__':
    gtkWin = GtkImageTrim()
    gtkWin.show()

